package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    private final FileStorageService fileStorageService;

    /**
     * 上传材料
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minio
        String originalFilename = multipartFile.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString();
        String fileId = null;
        try {
            fileId = fileStorageService.uploadHtmlFile("", fileName + type, multipartFile.getInputStream());
            log.info("上传成功,fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败");
        }

        //3.保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表 查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        log.info("素材列表查询参数:{}", dto);
        //1. 检查参数
        dto.checkParam();
        //2.分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //2.1 按照用户查询
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        //2.2是否收藏

        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //2.3按时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page, wrapper);
        //3.结果返回
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    private final WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //wmNewsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id))
        List<WmNewsMaterial> list = wmNewsMaterialMapper.check(id);
        log.info("该素材正在使用中:{}", list);
        if (list != null && !list.isEmpty()) {
            log.info("该素材正在使用中，不可删除");
            return ResponseResult.errorResult(501, "该素材正在使用中，不可删除");
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial != null) {
            log.info("删除文件:{}", wmMaterial);
            removeById(id);

        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.errorResult(200, "删除成功");
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial != null) {
            if (wmMaterial.getIsCollection() == 0) {
                wmMaterial.setIsCollection((short) 1);
            } else {
                wmMaterial.setIsCollection((short) 0);
            }
            updateById(wmMaterial);
        }
        return ResponseResult.okResult(200, "操作成功");
    }


}
